package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

@Transactional
@Service(interfaceClass = MemberService.class)
public class MemberServiceImpl implements MemberService {
    @Autowired
    MemberDao memberDao;

    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    public int add(Member member) {
        String password = member.getPassword();
        if (!StringUtils.isEmpty(password)) {
            String pwd = MD5Utils.md5(password);
            member.setPassword(pwd);
        }
        return memberDao.add(member);
    }

    @Override
    public Member register(String telephone) {
        Member member = memberDao.findByTelephone(telephone);
        if (member == null) {
            //当前用户不是会员，需要添加到会员表
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberDao.add(member);
        }
        return member;
    }

    @Override
    public Map getMemberReport() {
        List list = memberDao.getMemberReport();
        List<String> dateList = new ArrayList<>();
        List<Long> numList = new ArrayList<>();
        List<Long> allNumList = new ArrayList<>();
        long allNum = 0;
        for (Object o : list) {
            HashMap map = (HashMap) o;
            dateList.add((String) map.get("dates"));
            long number = (Long) map.get("number");
            numList.add(number);
            allNum = allNum + number;
            allNumList.add(allNum);
        }
        HashMap<String, List> map = new HashMap<>();
        map.put("months", dateList);
        map.put("memberCount", numList);
        map.put("allMember", allNumList);
        return map;
    }
}
